package com.taxis.service;

import java.util.List;
import org.hibernate.*;
import com.taxis.common.*;
import com.taxis.model.Bitacora;

public class BitacoraDaoService {

	private List<Bitacora> bitacoras;
	private Bitacora bitacora;

	public BitacoraDaoService(){ }

	public void insertBitacora(Bitacora b) throws Exception{
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			session.save(b);
			tx.commit();
		}catch(RuntimeException re){
			if(b != null){
				tx.rollback();
			}
			throw re;
		}finally{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Bitacora> getAllBitacoras() {
		Session session = HibernateUtil.currentSession();
		try {
			Query q = session.getNamedQuery("getAllBitacoras");
			bitacoras = (List<Bitacora>)q.list();
			return bitacoras;
		} catch(Exception e) {
			System.out.println("Error while fetching BITACORAS");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}

	public Bitacora getBitacora(Integer idBitacora) throws Exception {
		Session session = HibernateUtil.currentSession();
		try {
			return (Bitacora)session.get(Bitacora.class, idBitacora);
		} finally {
			session.close();
		}
	}

	public void updateBitacora(Bitacora b) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(b);
			tx.commit();
		} catch(RuntimeException re) {
			if(b != null)
				tx.rollback();
			throw re;
		} finally {
			session.close();
		}
	}

	public void deleteBitacora(Integer idBitacora) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			bitacora = (Bitacora)session.load(Bitacora.class, idBitacora);
			session.delete(bitacora);
			tx.commit();
		} catch (RuntimeException e) {
			if(bitacora != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
}